import React, { Component } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Modal, InputNumber, Row, Col,
} from 'antd';
import { FormComponentProps } from '@ant-design/compatible/es/form';

let timer: any;

interface RechargeInfoProps extends FormComponentProps {
  visible: boolean;
  formValues: {
    fcs_id: number,
    fcs_name: string,
    amount: number,
  };
  fetchAction: (typeName: string, params: any) => void;
  changeModal: (visible: boolean) => void;
  orderInfo?: any;
  orderResults?: boolean;
}

interface RechargeInfoState {
  submitLoading: boolean;
  codeShow: boolean;
  codeURL: string;
  chargeMoney: number;
  topUpMoney: any;
}

function mapStateToProps(state: any) {
  const {
    rechargeMoney: {
      orderInfo,
      orderResults,
    },
  } = state;

  return {
    orderInfo,
    orderResults,
  };
}

@connect(mapStateToProps)

class RechargeInfoElem extends Component<RechargeInfoProps, RechargeInfoState> {
  state = {
    submitLoading: false,
    codeShow: false,
    codeURL: '',
    chargeMoney: 0,
    topUpMoney: 0.1,
  }

  static getDerivedStateFromProps(nextProps: RechargeInfoProps, perState: RechargeInfoState) {
    const { codeShow } = perState;
    const {
      orderInfo,
      orderInfo: { createOrder },
      fetchAction,
      orderResults,
      changeModal,
    } = nextProps;

    if (orderResults) {
      clearInterval(timer);
      fetchAction('init', false);
      changeModal(false);
      return {
        codeShow: false,
        submitLoading: false,
        codeURL: '',
      };
    }

    if (!orderResults && orderInfo.serial_num && createOrder) {
      timer = setInterval(() => {
        fetchAction('orderStatus', { serial_num: orderInfo.serial_num });
      }, 1000);
    }

    if (codeShow !== createOrder) {
      return {
        codeShow: createOrder,
        codeURL: orderInfo.qrcode_img,
        chargeMoney: orderInfo.amount,
      };
    }
    return null;
  }

  handleSubmit = () => {
    const { formValues, fetchAction, form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        this.setState({
          submitLoading: true,
        }, () => {
          const params = {
            ...formValues,
            ...values,
          };
          fetchAction('recharge', params);
        });
      }
    });
  }

  handleCancel = () => {
    const { changeModal, fetchAction } = this.props;
    changeModal(false);
    clearInterval(timer);
    fetchAction('init', false);
    this.setState({
      codeShow: false,
      submitLoading: false,
      codeURL: '',
    });
  }

  changeMoney = (e: any) => {
    const { target: { value } }: any = e;
    const { form: { resetFields } } = this.props;
    resetFields(['amount']);
    this.setState({
      topUpMoney: value ? parseFloat(value).toFixed(2) : 0.1,
    });
  }

  render() {
    const {
      submitLoading,
      codeShow,
      codeURL,
      chargeMoney,
      topUpMoney,
    }: any = this.state;
    const { visible, formValues, form: { getFieldDecorator } } = this.props;

    return (
      <Modal
        title="账户充值"
        visible={visible}
        destroyOnClose
        okText="充值"
        style={{ top: 200 }}
        confirmLoading={submitLoading}
        className={codeShow && 'nodalHideBtn'}
        onOk={this.handleSubmit}
        onCancel={this.handleCancel}
      >
        <Form hideRequiredMark className="tableListForm">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }} style={{ marginBottom: 24 }}>
            <Col span={16} offset={4}>
              <div style={{ color: 'rgba(0,0,0,0.85)' }}>
                合作商名称：
                <span style={{ color: '#666' }}>{formValues.fcs_name}</span>
              </div>
            </Col>
          </Row>
          <Row gutter={12}>
            {!codeShow && (
              <Col span={16} offset={4}>
                <Form.Item label="充 值 金 额" style={{ marginBottom: 0 }}>
                  {getFieldDecorator('amount', {
                    initialValue: topUpMoney,
                    rules: [{ required: true, message: '请输入充值金额' }],
                  })(
                    <InputNumber
                      placeholder="请输入"
                      min={0.1}
                      max={99999999}
                      style={{ width: '100%' }}
                      onBlur={this.changeMoney}
                    />,
                  )}
                </Form.Item>
              </Col>
            )}
            {codeShow && (
              <Col span={16} offset={4}>
                <div style={{ color: 'rgba(0,0,0,0.85)' }}>
                  充 值 金 额：
                  <span style={{ color: '#666' }}>{chargeMoney} 元</span>
                </div>
                <div style={{ width: '100%', padding: '10%' }}>
                  <img style={{ width: '100%' }} src={codeURL} alt="" />
                </div>
                <p style={{ fontSize: 14, color: '#999' }}>充值二维码5分钟内有效，请及时完成充值操作</p>
              </Col>
            )}
          </Row>
        </Form>
      </Modal>
    );
  }
}

export default Form.create<RechargeInfoProps>()(RechargeInfoElem);
